﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;

using NineRays.WebControls;
using SD.LLBLGen.Pro.ORMSupportClasses;

using VitalShining.WebControls;
using CARMSBusiness;
using CARMSBusiness.InterFace;
using CARMSData.HelperClasses;

namespace CARMS.Admin
{
    [Function("Admin.EventManage")]
    public partial class EventManage : PageBase
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtStartDate_CalendarExtender.Format = ApplicationConfiguration.DateFormat;
                txtEndDate_CalendarExtender.Format = ApplicationConfiguration.DateFormat;


                LoadCategories();
                ShowLogs();
            }
        }

        private void LoadCategories()
        {

            foreach (var category in LogBusiness.GetLogCategories())
            {
                treeCategories.Nodes.Add(new FlyTreeNode(category, category));
            }
            if (treeCategories.Nodes.Count > 0)
            {
                treeCategories.SelectedNode = treeCategories.Nodes[0];
            }
        }

        protected void pagerLogs_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {
            SortExpression sort;
            switch (gridLogs.SortExpression)
            {
                //case "Type":
                //    sort = new SortExpression(LogFields.Level | (SortOperator)(int)gridLogs.SortDirection);
                //    break;
                case "UserName":
                    sort = new SortExpression(LogFields.UserName | (SortOperator)(int)gridLogs.SortDirection);
                    break;

                case "LogTime":
                    sort = new SortExpression(LogFields.LogTime | (SortOperator)(int)gridLogs.SortDirection);
                    break;
                case "LogOutTime":
                    sort = new SortExpression(LogFields.LogOutTime | (SortOperator)(int)gridLogs.SortDirection);
                    break;
                case "Duration":
                    sort = new SortExpression(LogFields.Duration | (SortOperator)(int)gridLogs.SortDirection);
                    break;
                case "IPAddress":
                    sort = new SortExpression(LogFields.VistorIp | (SortOperator)(int)gridLogs.SortDirection);
                    break;
                case "Source":
                    sort = new SortExpression(LogFields.Source | (SortOperator)(int)gridLogs.SortDirection);
                    break;
                case "User":
                    sort = new SortExpression(LogFields.UserName | (SortOperator)(int)gridLogs.SortDirection);
                    break;
                default:
                    sort = new SortExpression(LogFields.LogTime | SortOperator.Descending);
                    break;
            }


            e.DataSource = LogBusiness.GetLogList((PredicateExpression)e.Condition, sort, e.PageSize, e.PageIndex + 1);
        }

        protected void pagerLogs_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            e.RecordCount = LogBusiness.GetLogList().Count;
        }

        protected void pagerLogs_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var condition = new PredicateExpression();
          

            DateTime dateBegin;
            DateTime dateEnd;
            if (!string.IsNullOrEmpty(txtStartDate.Text.Trim()))
            {
                if (DateTime.TryParseExact(txtStartDate.Text, ApplicationConfiguration.DateFormat, ApplicationConfiguration.DateTimeFormatInfo, DateTimeStyles.AllowWhiteSpaces, out dateBegin))
                {
                    condition.Add(LogFields.LogTime >= dateBegin.Date);
                }
                else
                {
                    base.Alert("Please input a correct date format in the Login Time From column.");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(txtEndDate.Text.Trim()))
            {
                if (DateTime.TryParseExact(txtEndDate.Text, ApplicationConfiguration.DateFormat, ApplicationConfiguration.DateTimeFormatInfo, DateTimeStyles.AllowWhiteSpaces, out dateEnd))
                {
                    condition.Add(LogFields.LogTime < dateEnd.Date.AddDays(1));
                }
                else
                {
                    base.Alert("Please input a correct date format in the Login Time To column.");
                    return;
                }
            }


            if (!string.IsNullOrEmpty(txtUser.Text.Trim()))
            {
                condition.Add(LogFields.UserName % ("%" + txtUser.Text.Trim() + "%"));
            }
            e.Condition = condition;
        }

        protected void gridLogs_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var btnView = e.Row.FindControl("btnView") as ImageButton;
                if (btnView != null)
                {
                    btnView.OnClientClick = string.Format("showEventView('{0}');return false;",
                                                          DataBinder.Eval(e.Row.DataItem, "LogId"));
                }
            }
        }



        protected void btnSearch_Click(object sender, EventArgs e)
        {
            DateTime dateBegin;
            DateTime dateEnd;

            if (txtStartDate.Text.Trim().Length > 0 && !DateTime.TryParseExact(txtStartDate.Text.Trim(), ApplicationConfiguration.DateFormat, ApplicationConfiguration.DateTimeFormatInfo, DateTimeStyles.AllowWhiteSpaces, out dateBegin))
            {
                base.Alert("Please input the start date in a correct date format.");
                return;
            }

            if (txtEndDate.Text.Trim().Length > 0 && !DateTime.TryParseExact(txtEndDate.Text.Trim(), ApplicationConfiguration.DateFormat, ApplicationConfiguration.DateTimeFormatInfo, DateTimeStyles.AllowWhiteSpaces, out dateEnd))
            {
                base.Alert("Please input the end date in a correct date format.");
                return;
            }


            pagerLogs.PerformQuery();
        }

        private void ShowLogs()
        {
            if (treeCategories.SelectedNode != null)
            {
                btnSearch.Enabled = true;
                foreach (FlyTreeNode node in treeCategories.Nodes)
                {
                    node.ImageUrl = node.Selected ? ApplicationImages.TreeNodeOpened : ApplicationImages.TreeNodeClosed;
                }
                pagerLogs.PerformQuery();
            }
            else
            {
                btnSearch.Enabled = false;
            }
        }

        protected void btnChangeCategory_Click(object sender, EventArgs e)
        {
            txtUser.Text = string.Empty;
            txtStartDate.Text = string.Empty;
            txtEndDate.Text = string.Empty;
            //ddlLogLevel.SelectedValue = string.Empty;
            ShowLogs();
        }

        protected void gridLogs_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteEvent":
                    LogBusiness.DeleteLog(int.Parse(e.CommandArgument.ToString()));
                    ShowLogs();
                    break;
            }
        }

    }
}
